package cn.wdm.ymcc.service.impl;

import cn.wdm.ymcc.domain.AlipayInfo;
import cn.wdm.ymcc.domain.PayOrder;
import cn.wdm.ymcc.dto.AlipayNotifyDto;
import cn.wdm.ymcc.dto.PayNotifyDto;
import cn.wdm.ymcc.dto.ToScanCodeViewDto;
import cn.wdm.ymcc.exception.GloablException;
import cn.wdm.ymcc.service.IAlipayInfoService;
import cn.wdm.ymcc.service.IPayOrderService;
import cn.wdm.ymcc.service.IPayService;
import cn.wdm.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.page.Client;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

@Service
public class PayServiceImpl implements IPayService {
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    /**
     * 根据订单号查询支付单
     * @param orderNo
     * @return
     */
    @Override
    public PayOrder checkPayOrder(String orderNo) {
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        return payOrder;
    }

    /**
     * 发起支付请求，打开扫码界面
     * @param dto
     * @return String为扫码的界面 form的html
     */
    @Override
    public String openScanCodeView(ToScanCodeViewDto dto) {
        //1.校验参数不为空
        //2.根据订单号，查询订单的状态，只能为待支付才能去支付。
        PayOrder payOrder = payOrderService.selectByOrderNo(dto.getOrderNo());
        AssertUtil.isNotNull(payOrder,"payOrder支付单不存在");
        boolean payState = payOrder.getPayStatus() == PayOrder.STATE_WAIT_PAY;
        AssertUtil.isTrue(payState,"订单状态异常，不能支付");
        //3.根据支付类型为支付宝，去调支付宝
        if(dto.getPayType()==1){//调支付宝支付
            return alipay(payOrder,dto);
        }
        return null;
    }

    /**
     * 支付宝异步通知我们平台
     *  如果返回success给支付宝，那么支付宝不再通知你了
     *  如果返回的是非success，那么支付宝会一直尝试通知您，直到8次通知
     * @param dto
     * @return
     */
    @Override
    public String asynNotify(AlipayNotifyDto dto) throws Exception {
        System.out.println("回调处理impl");
        //1.将参数转为map集合
        String jsonStr = JSON.toJSONString(dto);
        Map<String,String> map = JSONObject.parseObject(jsonStr, Map.class);
        //2.校验身份（支付宝回调到我们，需要校验对方的身份,校验支付宝给我发的信息）
        Boolean isValid = Factory.Payment.Common().verifyNotify(map);
        //校验不正确，需要重新让支付宝发送消息
        if(!isValid){
            return "Fail";
        }
        //2.1,校验给我们发的支付消息，是不是正确的。是不是我们的订单，订单状态是不是待支付
        PayOrder payOrder = payOrderService.selectByOrderNo(dto.getOut_trade_no());
        if(payOrder==null){
            return "Fail";
        }
        if(payOrder.getPayStatus() == PayOrder.STATE_CANCEL){//如果支付单已经被取消，但是支付宝支付成功的消息回来了
            try {
                //调用退款
                AlipayTradeRefundResponse refund = Factory.Payment.Common()
                        .refund(payOrder.getOrderNo(), payOrder.getAmount().toString());
            } catch (Exception e) {
                e.printStackTrace();
                /**
                 * 做兜底
                 * 2.保存要取消支付单的记录到数据库，运维人员来人工跟进
                 * 3.给运维人员发站内信，邮件，消息---- 对接钉钉推销
                 */
            }
            return "success";
        }
        if(payOrder.getPayStatus()!=PayOrder.STATE_WAIT_PAY){
            return "Fail";
        }
        String trade_status = dto.getTrade_status();
        if(!trade_status.equals(AlipayNotifyDto.TRADE_SUCCESS)){
            return "Fail";
        }
        //2.处理支付成功的回调逻辑
        //注意：支付宝回调的时候，调Notify的controller，要内网穿透，其次调的是pay-service，我要修改订单和课程的user-learn
        //是跨微服，我们这里不用feign，是往mq中丢一个公用消息订单号.购买人.课程id，PayNotifyDto。然后course和order去广播消费
        //2.1 修改支付单的状态
        payOrder.setPayStatus(PayOrder.STATE_PAY_SUCCESS);
        payOrder.setUpdateTime(new Date());
        //2.1.1 包装消息体
        PayNotifyDto payNotifyDto = new PayNotifyDto();
        payNotifyDto.setOrderNo(payOrder.getOrderNo());
        payNotifyDto.setExtParams(payOrder.getExtParams());
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payNotifyDto)).build();
        //2.1.2 发送事务消息
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "asynNotifyTransaction",//该事务消息类型的别名
                "asynnotifymsg-topic:asynnotifymsg-tag",
                message,
                payOrder
        );
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if(localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK ){
            throw new GloablException("处理支付成功结果失败！！");
            //@TODO 向数据库记录：支付宝已经回到了我们，但是我们没有发布消息成功
        }
        //2.2 修改订单的的支付状态
        //2.3 添加用户的购买记录，给他授权


        return "success";
    }

    /**
     * 调用支付宝支付，返回Form表单
     * @return
     * @throws Exception
     */
    public String alipay(PayOrder payOrder,ToScanCodeViewDto dto){
        AlipayInfo info = alipayInfoService.selectOne(null);
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions(info));
        try {
            // 2. 网页端支付
            Client page = Factory.Payment.Page();
            //封装支付相关参数，发起支付
            AlipayTradePagePayResponse response = page.pay(
                    payOrder.getSubject(),
                    payOrder.getOrderNo(),
                    payOrder.getAmount().toString(),
                    StringUtils.isEmpty(dto.getCallUrl())?info.getReturnUrl():dto.getCallUrl()//同步回调地址
            );
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                return response.getBody();//Form表单
            } else {
                System.err.println("调用失败，原因：");
                throw new GloablException("支付调用失败！！！");
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    public Config getOptions(AlipayInfo info) {
        Config config = new Config();
        config.protocol = info.getProtocol();
        config.gatewayHost = info.getGatewayHost();//沙箱API地址
        config.signType = info.getSignType();
        config.appId = info.getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = info.getMerchantPrivateKey();
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = info.getAlipayPublicKey();
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = info.getNotifyUrl();
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        config.encryptKey = "";
        return config;
    }

}
